package org.grayrabbit.cloud.utils.manager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cloud.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class UserManager {
	private static final Logger logger = LoggerFactory.getLogger(UserManager.class);
	public void setPasswdPath(String passwdPath) {
		this.passwdPath = passwdPath;
	}

	public UserManager(){};
	
	public UserManager(String path){
		this.passwdPath = path;
	}
	private String passwdPath;
	/**
	 * 创建用户登录帐号
	 * @param userId 登录帐号
	 * @param pwd	密码
	 * @return
	 */
	public OperateState addUser(String userId,String pwd){
		try {
			List<String> records = read();
			List<String> users = getUserIds(records);
			if(users.contains(userId)){
				return OperateState.existuser;
			}
			String md5pwd = MD5.getMD5Str(pwd);
			records.add(userId+"::"+md5pwd);
			write(records);
		} catch (IOException e) {
			return OperateState.fail;
		}
		return OperateState.success;
	}
	/**
	 * 列出所有用户
	 * @return 登录帐号列表
	 * @throws IOException
	 */
	public List<String> listUser() throws IOException{
		return getUserIds(read());
	}
	
	private List<String> getUserIds(List<String> records){
		List<String> list = new ArrayList<String>();
		for(String s : records){
			if(s==null) continue;
			String[] arr = s.split("::");
			if(arr.length!=2) continue;
			list.add(arr[0]);
		}
		return list;
	}
	/**
	 * 修改密码
	 * @param userId 登录帐号
	 * @param oldPwd 原密码
	 * @param newPwd 新密码
	 * @return
	 */
	public OperateState modifyPwd(String userId,String oldPwd,String newPwd){
		
		try {
			List<String> records = read();
			List<String> users = getUserIds(records);
			if(!users.contains(userId)){
				return OperateState.notexistuser;
			}
			String oldString = userId + "::"+ MD5.getMD5Str(oldPwd);
			
			if(records.contains(oldString)){
				int index = records.indexOf(oldString);
				records.remove(index);
				String newString = userId + "::"+ MD5.getMD5Str(newPwd);
				records.add(index, newString);
				write(records);
			}else{
				return OperateState.errorpwd;
			}
			
		} catch (IOException e) {
			return OperateState.fail;
		}
		
		return OperateState.success;
	}
	/**
	 * 删除用户帐号
	 * @param userId 登录帐号
	 * @return
	 */
	public OperateState delUser(String userId){
		if("admin".equals(userId)){
			return OperateState.deladmin;
		}
		try {
			List<String> records = read();
			List<String> users = getUserIds(records);
			if(!users.contains(userId))
				return OperateState.notexistuser;
			int index = users.indexOf(userId);
			records.remove(index);
			write(records);
		} catch (IOException e) {
			return OperateState.fail;
		}
		
		return OperateState.success;
	}
	
	public enum OperateState{
		success,existuser,fail,errorpwd,notexistuser,deladmin;
	}
	
	public List<String> read() throws IOException{
		if(StringUtils.isBlank(passwdPath)){
			passwdPath = "passwd";
		}
		List<String> list = new ArrayList<String>();
		File f = new File(passwdPath);
		logger.debug("passwd文件目录：{}",f.getAbsolutePath());
		if(!f.exists()){
			f.createNewFile();
			addUser("admin","123456");
		}
		BufferedReader filePwd=new BufferedReader(new FileReader(passwdPath));
		String temp;
		do{
			temp = filePwd.readLine();
			if(!StringUtils.isBlank(temp))
				list.add(temp);
		}while(temp!=null);
		filePwd.close();
		return list;
	}
	
	public boolean validate(String user,String pwd) throws IOException{
		List<String> records = read();
		String md5pwd = user + "::"+ MD5.getMD5Str(pwd);
		if(records.contains(md5pwd)){
			return true;
		}
		return false;
	}
	
	public void write(List<String> records) throws IOException{
		if(StringUtils.isBlank(passwdPath)){
			passwdPath = "passwd";
		}
		BufferedWriter filePwd=new BufferedWriter(new FileWriter(new File(passwdPath),false));
		for(String s : records){
			filePwd.write(s);
			filePwd.newLine();
		}
		filePwd.flush();
		filePwd.close();
	}
	/**
	 * 敬告，此方法严禁正常调用，仅在单元测试中使用[删除passwd文件]
	 * 
	 */
	public void deletePwdFile(){
		if(StringUtils.isBlank(passwdPath)){
			passwdPath = "passwd";
		}
		File f = new File(passwdPath);
		f.deleteOnExit();
	}
}
